package com.qdlc.p2p.biz.util;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.core.redis.JedisCache;
import com.qdlc.p2p.common.core.redis.JedisCacheFactory;
import com.qdlc.p2p.common.util.ip.IPUtil;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserCache;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 处理分布式用户登录，负责存储、获取用户的登录信息，以及最后一次操作时间，保证用户登录的有效性;
 * @author linya 2016-02-15
 */
public class UserLoginUtil {

	//登录用户ID
    public static final String LOGIN_USER = "login_userid_";
    
    //用户最后操作时间
    public static final String USER_LAST_OPARETE_TIME = "user_last_oparete_time_";
	
    //设置缓存心跳时间，保证缓存最小心跳为1分钟，防止频繁更新缓存
    public static final Long HEARTBIT_TIME = TimeUnit.MINUTES.toMillis(1);
    
    public static final JedisCache<Long> jedisCache = JedisCacheFactory.newInstance(Long.class);
    
    /**
     * 获取登录用户
     * @return
     */
    public static User getLoginUser(){
    	HttpServletRequest request = ServletActionContext.getRequest();
    	return getLoginUser(request);
    }
    
    public static User getLoginUser(HttpServletRequest request){
    	
    	//获取Session uuid
    	String uuid = (String)request.getSession().getAttribute(LOGIN_USER);
    	if(uuid == null){
    		return null;
    	}
    	
    	//获取登录用户ID
    	Long userId = jedisCache.get(LOGIN_USER + uuid);
    	if(userId == null){
    		return null;
    	}
    	
    	User user = UserUtils.getUserById(userId);
    	return user;
    	
    }
    
    /**
     * 缓存登录用户ID
     * @param userId
     */
    public static void cacheLoginUser(long userId){
    	HttpServletRequest request = ServletActionContext.getRequest();
    	String uuid = UUID.randomUUID().toString();
    	HttpSession session = request.getSession();
    	session.setMaxInactiveInterval(30 * 60);
    	session.setAttribute(LOGIN_USER, uuid);
    	jedisCache.set(LOGIN_USER + uuid, userId, 30, TimeUnit.MINUTES);
    	jedisCache.set(USER_LAST_OPARETE_TIME + uuid, System.currentTimeMillis());
    }
    
    public static void cleanLoginUser(){
    	HttpServletRequest request = ServletActionContext.getRequest();
    	String uuid = (String)request.getSession().getAttribute(LOGIN_USER);
    	jedisCache.delete(LOGIN_USER + uuid);
    	jedisCache.delete(USER_LAST_OPARETE_TIME + uuid);
    }
    
	/**
	 * 保存缓存信息有效性
	 * @param force 强迫更新Session
	 */
	public static void heartbit(boolean force){
		HttpServletRequest request = ServletActionContext.getRequest();
		String uuid = (String)request.getSession().getAttribute(LOGIN_USER);
		Long lastTime = jedisCache.get(USER_LAST_OPARETE_TIME + uuid);
		if(lastTime == null){
			return;
		}
		
		//更新登录用户ID的过期时间
		if(force || (lastTime + HEARTBIT_TIME > System.currentTimeMillis())){
			Long userId = jedisCache.get(LOGIN_USER + uuid);
			if(userId != null){
				jedisCache.set(LOGIN_USER + uuid, userId, 30, TimeUnit.MINUTES);
				UserCache userCache = UserUtils.getUserCacheByUserId(userId);
				UserIdentify userIdentify = UserUtils.getUserIdentify(userId);
	            HttpSession session = request.getSession();
	            User user = UserUtils.getUserById(userId);
	            session.setAttribute(Constant.SESSION_USER, user);
	            session.setAttribute("userCache", userCache);
	            session.setAttribute(Constant.SESSION_USER_IDENTIFY, userIdentify);
			}
		} 
	}
	
	public static UserIdentify getUserIdentify(){
		User user = getLoginUser();
		UserIdentify userIdentify = UserUtils.getUserIdentify(user);
		return userIdentify;
	}
	
}
